"use strict";
/*
 * @Desc         : 文件用tsc编译成Js。放在服务端仓库用于修改protoc生成的java代码
 * @Author       :
 * @Date         : 2024-06-19 16:52:33
 * @LastEditTime : 2025-04-23 17:23:33
 * @LastEditors  : sc
 * @FilePath     : /TsTools/Source/ToolsExternal/TransferProtoJava/TransferProtoJava.ts
 */
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransferProtoJava = void 0;
var path = require("path");
var fs = require("fs");
var readline = require("readline");
var TransferProtoJava = /** @class */ (function () {
    function TransferProtoJava() {
    }
    TransferProtoJava.prototype.Main = function () {
        console.log("=====开始=====");
        var oOption = this.GetOption();
        console.log("命令行选项 =", JSON.stringify(oOption));
        var sTargetFile = oOption["file"] ? oOption["file"] : "";
        var sFolder = __dirname;
        this.TransferDir(sFolder, sTargetFile);
    };
    TransferProtoJava.prototype.TransferDir = function (sFolder, sTargetFile) {
        var iStartTime = performance.now();
        var sProtoFolderPath = path.resolve(sFolder, "proto");
        var sJavaFolderPath = path.resolve(sFolder, "src/main/java/com/motu/monstercity/protocol");
        //遍历proto文件夹，读取所有proto文件
        var tFiles = fs.readdirSync(sProtoFolderPath);
        var tPromises = [];
        for (var _i = 0, tFiles_1 = tFiles; _i < tFiles_1.length; _i++) {
            var sFile = tFiles_1[_i];
            var sFullPath = path.resolve(sProtoFolderPath, sFile);
            var oStats = fs.statSync(sFullPath);
            var bIsDir = oStats.isDirectory(); //是文件夹
            if (bIsDir && !sFile.startsWith(".")) {
                console.log("子文件夹:" + sFile);
                continue;
            }
            if (sFile.indexOf(".proto") == -1) {
                continue;
            }
            if (sTargetFile != "" && sFile != sTargetFile) {
                continue;
            }
            //分离文件名和后缀
            var tFile = sFile.split(".");
            var sJavaPath = path.resolve(sJavaFolderPath, this.NameCamelCase(tFile[0]) + ".java");
            console.log("sFullPath:", sFullPath);
            console.log("sJavaPath:", sJavaPath);
            if (!fs.existsSync(sJavaPath)) {
                console.error("Java文件不存在:", sJavaPath);
            }
            var oPromise = this.TransferProtoJava(sFullPath, sJavaPath);
            tPromises.push(oPromise);
        }
        Promise.all(tPromises).then(function () {
            console.log("=======全部转换完成=======");
            var iEndTime = performance.now();
            console.log("\u603B\u8017\u65F6:".concat((iEndTime - iStartTime) / 1000, " s. \u8F6C\u6362\u6587\u4EF6\u6570:").concat(tPromises.length));
        });
    };
    TransferProtoJava.prototype.TransferProtoJava = function (sProtoPath, sJavaPath) {
        // const startTime = performance.now();
        var _this = this;
        var protoContent = fs.readFileSync(sProtoPath, "utf-8");
        var tMatch = this.MatchProtoMessages(protoContent);
        // console.log(tMatch);
        // 调用函数并打印结果
        // let tMatch = this.MatchProtoPropertyNames(protoContent);
        // console.log(tMatch);
        //去掉tMatch的重复元素
        // tMatch = Array.from(new Set(tMatch));
        // console.log(tMatch);
        if (Object.keys(tMatch).length == 0) {
            return new Promise(function (resolve) {
                resolve();
            });
        }
        var sJavaContent = "";
        var sCurrentMessageClassName = "";
        var sCurrentMethodName = "";
        var sWriteToMethodContent = ""; // 新增：收集writeTo方法的内容
        var bInWriteToMethod = false; // 新增：是否在writeTo方法内
        var iWriteToMethodBracketCount = 0; // 新增：writeTo方法的括号计数
        var oReadStream = fs.createReadStream(sJavaPath);
        var rl = readline.createInterface({
            input: oReadStream,
            crlfDelay: Infinity,
        });
        return new Promise(function (resolve) {
            rl.on("line", function (line) {
                //找到当前的message类名
                if (line.indexOf("public") != -1 && line.indexOf("static final class") != -1) {
                    //正则获取类名
                    var regex = /public\s+static final class\s+(\w+)/;
                    var match = regex.exec(line);
                    if (match && match[1] != "Builder") {
                        sCurrentMessageClassName = match[1];
                        // console.log("当前类名:", sCurrentMessageClassName);
                    }
                }
                //新增：找到当前的方法名
                if (line.indexOf("public") != -1 || line.indexOf("private") != -1) {
                    //正则匹配方法声明
                    var methodRegex = /(public|private)\s+(?:static\s+)?(?:<[^>]+>\s+)?[\w.<>]+\s+(\w+)\s*\(/;
                    var methodMatch = methodRegex.exec(line);
                    if (methodMatch && methodMatch[2]) {
                        sCurrentMethodName = methodMatch[2];
                        if (sCurrentMethodName === "writeTo") {
                            bInWriteToMethod = true;
                            iWriteToMethodBracketCount = 0;
                            // 检查当前行是否包含左花括号
                            iWriteToMethodBracketCount += (line.match(/{/g) || []).length;
                            sWriteToMethodContent = line + "\n";
                            return;
                        }
                        else if (sCurrentMethodName === "getSerializedSize") {
                            bInWriteToMethod = true;
                            iWriteToMethodBracketCount = 0;
                            // 检查当前行是否包含左花括号
                            iWriteToMethodBracketCount += (line.match(/{/g) || []).length;
                            sWriteToMethodContent = line + "\n";
                            return;
                        }
                        else if (sCurrentMessageClassName && tMatch[sCurrentMessageClassName]) {
                            var oMatchData = _this.GetMatchSetMethodName(sCurrentMethodName, tMatch[sCurrentMessageClassName]);
                            if (oMatchData.sName) {
                                bInWriteToMethod = true;
                                iWriteToMethodBracketCount = 0;
                                iWriteToMethodBracketCount += (line.match(/{/g) || []).length;
                                sWriteToMethodContent = line + "\n";
                                return;
                            }
                        }
                        // console.log("当前方法名:", sCurrentMethodName);
                    }
                }
                // 如果在writeTo或getSerializedSize方法内，收集内容
                if (bInWriteToMethod) {
                    sWriteToMethodContent += line;
                    iWriteToMethodBracketCount += (line.match(/{/g) || []).length;
                    iWriteToMethodBracketCount -= (line.match(/}/g) || []).length;
                    if (iWriteToMethodBracketCount === 0) {
                        bInWriteToMethod = false;
                        // 处理收集到的方法内容
                        if (sCurrentMessageClassName && tMatch[sCurrentMessageClassName]) {
                            // 先处理方法特有的修改
                            for (var _i = 0, _a = tMatch[sCurrentMessageClassName]; _i < _a.length; _i++) {
                                var oMatchData = _a[_i];
                                if (oMatchData.bIsRepeated && !oMatchData.bIsBaseType) {
                                    if (sCurrentMethodName === "writeTo") {
                                        sWriteToMethodContent = _this.ModifyWriteMessage(sWriteToMethodContent, oMatchData.sName);
                                    }
                                    else if (sCurrentMethodName === "getSerializedSize") {
                                        sWriteToMethodContent = _this.ModifyComputeMessageSize(sWriteToMethodContent, oMatchData.sName);
                                    }
                                }
                            }
                            // 处理set方法的特殊情况
                            var oSetMatchData = _this.GetMatchSetMethodName(sCurrentMethodName, tMatch[sCurrentMessageClassName]);
                            if (oSetMatchData.sName && oSetMatchData.bIsRepeated) {
                                var returnRegex = /return\s+this\s*;/g;
                                // console.log("sWriteToMethodContent:", sWriteToMethodContent);
                                sWriteToMethodContent = sWriteToMethodContent.replace(returnRegex, "has".concat(_this.FirstLetterUpper(oSetMatchData.sName), "_ = true;\n        return this;"));
                            }
                            // 对方法内容的每一行进行其他修改
                            var tLines = sWriteToMethodContent.split("\n");
                            sWriteToMethodContent = "";
                            for (var _b = 0, tLines_1 = tLines; _b < tLines_1.length; _b++) {
                                var line_1 = tLines_1[_b];
                                sWriteToMethodContent += _this.ProcessLine(line_1, tMatch, sCurrentMessageClassName) + "\n";
                            }
                        }
                        sJavaContent += sWriteToMethodContent;
                        sWriteToMethodContent = "";
                        return;
                    }
                    sWriteToMethodContent += "\n";
                }
                if (!bInWriteToMethod) {
                    if (line.indexOf("_") != -1 && sCurrentMessageClassName != "") {
                        line = _this.ProcessLine(line, tMatch, sCurrentMessageClassName);
                    }
                    sJavaContent += line + "\n";
                }
            });
            rl.on("close", function () {
                // console.log('File has been read');
                fs.writeFileSync(sJavaPath, sJavaContent);
                console.log("[转换完成]", path.basename(sJavaPath));
                // const endTime = performance.now();
                // console.log(`Function execution took ${endTime - startTime} milliseconds.`);
                resolve();
            });
        });
        // let sJavaContent = fs.readFileSync(sJavaPath, "utf-8");
        // let tJavaMatch = this.matchJavaPropertyNames(sJavaContent, tMatch);
        // console.log(tJavaMatch);
        // for (let sKey in tJavaMatch) {
        //     sJavaContent = this.AddNewBooleanVar(sJavaContent, sKey, tJavaMatch);
        //     sJavaContent = this.ModifyIfLines(sJavaContent, sKey);
        //     sJavaContent = this.ModifyBuildPartial(sJavaContent, sKey);
        //     sJavaContent = this.ModifySetProperty(sJavaContent, sKey);
        // }
        // //写入文件
        // fs.writeFileSync(sJavaPath, sJavaContent);
        // console.log("=====转换完成=====",sJavaPath);
        // const endTime = performance.now();
        // console.log(`Function execution took ${endTime - startTime} milliseconds.`);
    };
    TransferProtoJava.prototype.ProcessLine = function (line, tMatch, sCurrentMessageClassName) {
        var sNewLine = line;
        if (line.indexOf("_") != -1 && sCurrentMessageClassName != "") {
            var tJavaMatchKeyData = this.GetMatchJavaPropertyName(line, tMatch[sCurrentMessageClassName]);
            var sJavaMatchKey = tJavaMatchKeyData.sName;
            if (sJavaMatchKey != "") {
                sNewLine = this.AddNewBooleanVar(sNewLine, sJavaMatchKey);
                sNewLine = this.ModifyBuildPartial(sNewLine, sJavaMatchKey);
                sNewLine = this.ModifySetProperty(sNewLine, sJavaMatchKey);
                if (tJavaMatchKeyData.bIsRepeated) {
                    // const sHasLine = `has${this.FirstLetterUpper(sJavaMatchKey)}_ = true;`;
                    // sNewLine = this.AddNewLineAfterMatchLine(sNewLine, `\\s*${sJavaMatchKey}_\\.set.*`, sHasLine);
                    // sNewLine = this.AddNewLineAfterMatchLine(sNewLine, `\\s*${sJavaMatchKey}_\\.add\\(value\\);.*`, sHasLine);
                    // sNewLine = this.AddNewLineAfterMatchLine(sNewLine, `\\s*values, ${sJavaMatchKey}_\\);.*`, sHasLine);
                    // if (sCurrentMethodName != "clear" && sCurrentMethodName.indexOf("clear") != -1) {
                    //     sNewLine = this.AddNewLineAfterMatchLine(
                    //         sNewLine,
                    //         `\\s*${sJavaMatchKey}_ = java\\.util\\.Collections\\.emptyList\\(\\);`,
                    //         sHasLine
                    //     );
                    // }
                }
                else {
                    sNewLine = this.ModifyIfLines(sNewLine, sJavaMatchKey, "if[ ]*\\((?!!.*?".concat(sJavaMatchKey, "_).*").concat(sJavaMatchKey, "_.*\\)"));
                    sNewLine = this.ModifyIfLines(sNewLine, sJavaMatchKey, "if[ ]*\\([ ]*![ ]*".concat(sJavaMatchKey, "_\\.isEmpty\\(\\)[ ]*\\)"));
                }
            }
        }
        if (line.indexOf("List().size()") != -1 || line.indexOf("List().isEmpty()") != -1) {
            var tJavaMatchKeyData = this.GetMatchJavaFunctionName(line, tMatch[sCurrentMessageClassName]);
            var sJavaMatchKey = tJavaMatchKeyData.sName;
            if (sJavaMatchKey != "") {
                sNewLine = this.ModifyIfLines(sNewLine, sJavaMatchKey, "if \\(get".concat(this.FirstLetterUpper(sJavaMatchKey), "List\\(\\).size\\(\\) > 0\\)"));
                sNewLine = this.ModifyIfLines(sNewLine, sJavaMatchKey, "if \\(!get".concat(this.FirstLetterUpper(sJavaMatchKey), "List\\(\\)\\.isEmpty\\(\\)\\)"));
            }
        }
        if (line.indexOf("Bytes().size()") != -1 || line.indexOf("Bytes().isEmpty()") != -1) {
            var tJavaMatchKeyData = this.GetMatchJavaFunctionName(line, tMatch[sCurrentMessageClassName]);
            var sJavaMatchKey = tJavaMatchKeyData.sName;
            if (sJavaMatchKey != "") {
                sNewLine = this.ModifyIfLines(sNewLine, sJavaMatchKey, "if \\(!get".concat(this.FirstLetterUpper(sJavaMatchKey), "Bytes\\(\\)\\.isEmpty\\(\\)\\)"));
            }
        }
        return sNewLine;
    };
    TransferProtoJava.prototype.AddNewBooleanVar = function (sJavaContent, sKey) {
        //遍历tMatch，正则匹配java文件中存在的代码
        //比如requestData匹配private com.google.protobuf.ByteString requestData_;
        //比如netId匹配private int netId_;
        var sBooleanVarName = "has".concat(this.FirstLetterUpper(sKey), "_");
        // 修改正则表达式，使其同时匹配分号和等号结尾
        var regex = new RegExp(".*private .+ ".concat(sKey, "_.*?[;=]"), "gm");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        // console.log(tLines.join(" | "));
        tLines = Array.from(new Set(tLines));
        // console.log(tLines.join(" | "));
        for (var _i = 0, tLines_2 = tLines; _i < tLines_2.length; _i++) {
            var sContent = tLines_2[_i];
            //正则替换非空白字符
            //放到上一行，因为有的声明语句会换行变成两行，直接接在后面会插在代码中间导致错误
            var sNewContent = "".concat(sContent.replace(this.Trim(sContent), "private boolean ".concat(sBooleanVarName, ";")), "\n").concat(sContent);
            // sJavaContent = sJavaContent.replaceAll(sContent, sNewContent);
            sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.ModifyIfLines = function (sJavaContent, sKey, sReg) {
        var sBooleanVarName = "has".concat(this.FirstLetterUpper(sKey), "_");
        var regex = new RegExp(sReg, "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        // console.log(tLines.join(" | "));
        for (var _i = 0, tLines_3 = tLines; _i < tLines_3.length; _i++) {
            var sContent = tLines_3[_i];
            //正则替换sContent括号内的内容添加sBooleanVarName
            var iLastIndex = sContent.lastIndexOf(")");
            var sNewContent = sContent.substring(0, iLastIndex) + " || ".concat(sBooleanVarName) + sContent.substring(iLastIndex);
            sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.ModifyBuildPartial = function (sJavaContent, sKey) {
        var sBooleanVarName = "has".concat(this.FirstLetterUpper(sKey), "_");
        var sWord = "result.".concat(sKey, "_ = (?:").concat(sKey, "_|").concat(sKey, "Builder_\\.build\\(\\))");
        // console.log(sWord);
        var regex = new RegExp(".*".concat(sWord, ".*"), "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        // console.log(tLines.join(" | "));
        for (var _i = 0, tLines_4 = tLines; _i < tLines_4.length; _i++) {
            var sContent = tLines_4[_i];
            var sNewContent = "".concat(sContent, "\n").concat(sContent.replace(this.Trim(sContent), "result.".concat(sBooleanVarName, " = ").concat(sBooleanVarName, ";")));
            sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.ModifySetProperty = function (sJavaContent, sKey) {
        var sBooleanVarName = "has".concat(this.FirstLetterUpper(sKey), "_");
        var sWord = "".concat(sKey, "_ = value;");
        // console.log(sWord);
        var regex = new RegExp("\\s+".concat(sWord, ".*"), "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        // console.log(tLines.join(" | "));
        for (var _i = 0, tLines_5 = tLines; _i < tLines_5.length; _i++) {
            var sContent = tLines_5[_i];
            var sNewContent = "".concat(sContent, "\n").concat(sContent.replace(this.Trim(sContent), "".concat(sBooleanVarName, " = true;")));
            // sJavaContent = this.ReplaceAll(sJavaContent, '\n'+sContent, '\n'+sNewContent);//添加换行符匹配，用来识别不同的行
            sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.AddNewLineAfterMatchLine = function (sJavaContent, sMatchReg, sNewLine) {
        var regex = new RegExp(sMatchReg, "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        for (var _i = 0, tLines_6 = tLines; _i < tLines_6.length; _i++) {
            var sContent = tLines_6[_i];
            var sNewContent = "".concat(sContent, "\n").concat(sJavaContent.replace(this.Trim(sContent), sNewLine));
            sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.Trim = function (str) {
        // const reg = /^\s+|\s+$/g;
        // return str.replace(reg,'');
        return str.trim();
    };
    TransferProtoJava.prototype.ReplaceAll = function (sContent, sSearch, sReplace) {
        // return sContent.replaceAll(sSearch, sReplace);
        return sContent.split(sSearch).join(sReplace);
        // return sContent.replace(new RegExp(sSearch,'gm'), sReplace);
    };
    //首字母大写
    TransferProtoJava.prototype.FirstLetterUpper = function (str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    //改成逐行解析，只能匹配到一个
    TransferProtoJava.prototype.GetMatchJavaPropertyName = function (sJavaContent, tMatch) {
        for (var i = 0; i < tMatch.length; i++) {
            var sMatch = tMatch[i].sName;
            var regex = new RegExp("\\b".concat(sMatch, "_"), "g");
            var tResultMatch = this.FindAllMatches(sJavaContent, regex);
            if (tResultMatch.length > 0 && tResultMatch[0] != "") {
                return tMatch[i];
            }
        }
        return { sName: "", bIsRepeated: false, bIsBaseType: false };
    };
    TransferProtoJava.prototype.GetMatchJavaFunctionName = function (sJavaContent, tMatch) {
        for (var i = 0; i < tMatch.length; i++) {
            var sMatch = tMatch[i].sName;
            var regex = new RegExp(".*".concat(this.FirstLetterUpper(sMatch)), "g");
            var tResultMatch = this.FindAllMatches(sJavaContent, regex);
            if (tResultMatch.length > 0 && tResultMatch[0] != "") {
                return tMatch[i];
            }
        }
        return { sName: "", bIsRepeated: false, bIsBaseType: false };
    };
    //改成按message分组，减少代码遍历次数
    TransferProtoJava.prototype.MatchProtoMessages = function (protoContent) {
        //正则匹配单行注释
        var skipComments = /\/\/.*|\/\*[\s\S]*?\*\//g;
        //匹配proto中的message，使用更复杂的正则来处理嵌套结构
        var oRegexMessage = /message\s+(\w+)\s*{((?:[^{}]|(?:\{[^{}]*\}))*)}/g;
        var fullMatch;
        var result = {};
        // 首先，我们移除所有注释
        var sCleanedContent = protoContent.replace(skipComments, "");
        // 然后，我们在清理后的内容中查找属性名
        while ((fullMatch = oRegexMessage.exec(sCleanedContent)) !== null) {
            var sMessageName = fullMatch[1];
            var sMessageContent = fullMatch[2];
            result[sMessageName] = this.MatchProtoPropertyNames(sMessageContent);
        }
        return result;
    };
    TransferProtoJava.prototype.MatchProtoPropertyNames = function (protoContent) {
        //正则匹配单行注释
        var skipComments = /\/\/.*|\/\*[\s\S]*?\*\//g;
        // 首先，我们移除所有注释
        var cleanedContent = protoContent.replace(skipComments, "");
        var tMatchList = [];
        var oFullMatch;
        // 先匹配所有repeated字段（包括基础类型和自定义类型）
        var repeatedRegex = /repeated\s+([\w.]+)\s+([\w_]+)\s*=/g;
        var repeatedFields = new Set();
        var baseTypes = new Set(["bool", "int32", "uint32", "uint64", "string", "double", "float", "bytes"]);
        while ((oFullMatch = repeatedRegex.exec(cleanedContent)) !== null) {
            var fieldType = oFullMatch[1];
            var fieldName = oFullMatch[2];
            // fieldName要改为小写字母开头，生成的java代码里会自动改为小写
            fieldName = fieldName.charAt(0).toLowerCase() + fieldName.slice(1);
            repeatedFields.add(fieldName);
            tMatchList.push({
                sName: fieldName,
                bIsRepeated: true,
                bIsBaseType: baseTypes.has(fieldType),
            });
        }
        // 再匹配所有非repeated字段（只匹配基础类型）
        var nonRepeatedRegex = /(?<!repeated\s+)(bool|int32|uint32|uint64|string|double|float|bytes)\s+([\w_]+)\s*=/g;
        while ((oFullMatch = nonRepeatedRegex.exec(cleanedContent)) !== null) {
            var fieldName = oFullMatch[2];
            // fieldName要改为小写字母开头
            fieldName = fieldName.charAt(0).toLowerCase() + fieldName.slice(1);
            // 只有当字段名不在repeatedFields中时才添加
            if (!repeatedFields.has(fieldName)) {
                tMatchList.push({
                    sName: fieldName,
                    bIsRepeated: false,
                    bIsBaseType: true, // 非repeated只匹配基础类型，所以一定是基础类型
                });
            }
        }
        return tMatchList;
    };
    TransferProtoJava.prototype.NameCamelCase = function (sFileName) {
        var sOutName = "";
        sFileName.split("_").map(function (sItem) {
            sOutName += sItem.charAt(0).toUpperCase() + sItem.slice(1);
        });
        return sOutName;
    };
    TransferProtoJava.prototype.FindAllMatches = function (content, regex) {
        var matches = [];
        var match;
        while ((match = regex.exec(content)) !== null) {
            // 注意：match[0] 总是包含完整的匹配项
            matches.push(match[0]);
            // 如果你的正则表达式包含捕获组，并且你想要它们的数据，
            // 你可能需要处理 match[1], match[2], ...
            // 但在这个例子中，我们只关心完整的匹配项
            // 防止无限循环（在大多数情况下不是必需的，但理论上是好的做法）
            if (match.index === regex.lastIndex) {
                regex.lastIndex++;
            }
        }
        return matches;
    };
    TransferProtoJava.prototype.GetOption = function () {
        var tArgs = process.argv.slice(2); // 获取命令行参数数组
        var tResult = tArgs.reduce(function (tPre, sItem) {
            // 使用reduce方法对参数数组进行处理
            if (sItem.indexOf("=") !== -1) {
                // 判断参数是否有等号
                return __spreadArray(__spreadArray([], tPre, true), [sItem.split("=")], false); // 将带有等号的参数进行分割并添加到结果数组中
            }
            return tPre; // 否则返回原结果数组
        }, []);
        var oParams = Object.fromEntries(tResult); // 将结果数组转化为参数对象
        return oParams; // 返回参数对象
    };
    TransferProtoJava.prototype.ModifyWriteMessage = function (sJavaContent, sKey) {
        var regex = new RegExp("for\\s*\\(int\\s+i\\s*=\\s*0;\\s*i\\s*<\\s*".concat(sKey, "_\\.size\\(\\);\\s*i\\+\\+\\)\\s*{\\s*output\\.writeMessage\\((\\d+),\\s*").concat(sKey, "_\\.get\\(i\\)\\);\\s*}"), "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        for (var _i = 0, tLines_7 = tLines; _i < tLines_7.length; _i++) {
            var sContent = tLines_7[_i];
            var tagMatch = /writeMessage\((\d+)/.exec(sContent);
            if (tagMatch) {
                var tagNumber = tagMatch[1];
                var sNewContent = "if (".concat(sKey, "_.isEmpty() && has").concat(this.FirstLetterUpper(sKey), "_) {\n        output.writeTag(").concat(tagNumber, ", com.google.protobuf.WireFormat.WIRETYPE_LENGTH_DELIMITED);\n        output.writeUInt32NoTag(0);\n      } else {\n        ").concat(sContent, "\n      }");
                sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
            }
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.ModifyComputeMessageSize = function (sJavaContent, sKey) {
        var regex = new RegExp("for\\s*\\(int\\s+i\\s*=\\s*0;\\s*i\\s*<\\s*".concat(sKey, "_\\.size\\(\\);\\s*i\\+\\+\\)\\s*{\\s*size\\s*\\+=\\s*com\\.google\\.protobuf\\.CodedOutputStream\\s*\\.computeMessageSize\\((\\d+),\\s*").concat(sKey, "_\\.get\\(i\\)\\);\\s*}"), "g");
        var tLines = this.FindAllMatches(sJavaContent, regex);
        tLines = Array.from(new Set(tLines));
        for (var _i = 0, tLines_8 = tLines; _i < tLines_8.length; _i++) {
            var sContent = tLines_8[_i];
            var tagMatch = /computeMessageSize\((\d+)/.exec(sContent);
            if (tagMatch) {
                var tagNumber = tagMatch[1];
                var sNewContent = "if (get".concat(this.FirstLetterUpper(sKey), "List().isEmpty() && has").concat(this.FirstLetterUpper(sKey), "_) {\n        size += com.google.protobuf.CodedOutputStream.computeTagSize(").concat(tagNumber, ");\n        size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(0);\n      } else {\n        ").concat(sContent, "\n      }");
                sJavaContent = this.ReplaceAll(sJavaContent, sContent, sNewContent);
            }
        }
        return sJavaContent;
    };
    TransferProtoJava.prototype.GetMatchSetMethodName = function (sMethodName, tMatch) {
        // 检查方法名是否以set、add、addAll或clear开头
        if (!sMethodName.startsWith("set") &&
            !sMethodName.startsWith("addAll") &&
            !sMethodName.startsWith("add") &&
            !sMethodName.startsWith("clear") &&
            !sMethodName.startsWith("remove")) {
            return { sName: "", bIsRepeated: false, bIsBaseType: false };
        }
        for (var i = 0; i < tMatch.length; i++) {
            var sMatch = tMatch[i].sName;
            // 根据方法前缀构建完整的方法名
            var sExpectedMethodName = "";
            if (sMethodName.startsWith("set")) {
                sExpectedMethodName = "set".concat(this.FirstLetterUpper(sMatch));
            }
            else if (sMethodName.startsWith("addAll")) {
                sExpectedMethodName = "addAll".concat(this.FirstLetterUpper(sMatch));
            }
            else if (sMethodName.startsWith("add")) {
                sExpectedMethodName = "add".concat(this.FirstLetterUpper(sMatch));
            }
            else if (sMethodName.startsWith("clear")) {
                sExpectedMethodName = "clear".concat(this.FirstLetterUpper(sMatch));
            }
            else if (sMethodName.startsWith("remove")) {
                sExpectedMethodName = "remove".concat(this.FirstLetterUpper(sMatch));
            }
            if (sMethodName === sExpectedMethodName) {
                return tMatch[i];
            }
        }
        return { sName: "", bIsRepeated: false, bIsBaseType: false };
    };
    return TransferProtoJava;
}());
exports.TransferProtoJava = TransferProtoJava;
new TransferProtoJava().Main();
//test
// new TransferProtoJava().TransferDir("/Users/admin/Documents/server/huyao/huyao-protocol", "Base.proto");
